﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace PasteTimer.taskmodels
{

    /// <summary>
    /// 节点信息
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "node" })]
    public class NodeInfoAppService : IUserAppService
    {

        private ChannelHelper _channelHelper;
        private IPasteTimerDbContext _dbContext;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="channelHelper"></param>
        /// <param name="dbcontext"></param>
        public NodeInfoAppService(
            ChannelHelper channelHelper,
            IPasteTimerDbContext dbcontext)
        {
            _channelHelper = channelHelper;
            _dbContext = dbcontext;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagedResultDto<NodeInfoListDto>> GetListAsync(int page = 1, int size = 20)
        {

            var query = _dbContext.NodeInfo.Where(t => 1 == 1).OrderByDescending(xy => xy.Id);
            var _pagedto = new PagedResultDto<NodeInfoListDto>();
            _pagedto.TotalCount = await query.CountAsync();
            var userList = await query.Page(page, size).ToListAsync();
            var temList = ObjectMapper.Map<List<NodeInfo>, List<NodeInfoListDto>>(userList);
            _pagedto.Items = temList;
            return _pagedto;
        }


        /// <summary>
        /// 读取分组信息，用于下拉显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<NodeGroupInfoListDto>> Groups()
        {
            var _query = await _dbContext.NodeGroupInfo.Where(x => true).OrderBy(x => x.Id).AsNoTracking().ToListAsync();
            return ObjectMapper.Map<List<NodeGroupInfo>, List<NodeGroupInfoListDto>>(_query);
        }

        /// <summary>
        /// 根据ID获取单项节点信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public NodeInfoDto GetByIdAsync(int id)
        {
            var query = _dbContext.NodeInfo.Where(t => t.Id == id).FirstOrDefault();
            var temList = ObjectMapper.Map<NodeInfo, NodeInfoDto>(query);
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息节点信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public NodeInfoUpdateDto GetInfoForUpdateAsync(int id)
        {
            var query = _dbContext.NodeInfo.Where(t => t.Id == id).FirstOrDefault();
            var temList = ObjectMapper.Map<NodeInfo, NodeInfoUpdateDto>(query);
            return temList;
        }

        /// <summary>
        /// 添加一个节点信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork(false)]
        [HttpPost]
        public async Task<NodeInfoDto> CreateItemAsync(NodeInfoAddDto input)
        {
            var _userid = base.ReadCurrentAdminId();
            var newu = ObjectMapper.Map<NodeInfoAddDto, NodeInfo>(input);
            newu.IsEnable = true;//添加自定义
            newu.Status = NodeStatus.running;
            newu.JoinToken = Guid.NewGuid().ToString().Replace("-", "").ToLower();
            newu.Token = Guid.NewGuid().ToString().Replace("-", "").ToLower();
            _dbContext.Add(newu);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<NodeInfo, NodeInfoDto>(newu);
            var find_group = _dbContext.NodeGroupInfo.Where(x => x.Name == input.Group).Select(x => x.Id).FirstOrDefault();
            if (find_group == 0)
            {
                _dbContext.Add(new NodeGroupInfo
                {
                    Name = input.Group,
                    Description = "",
                    Sort = 1,
                    UserId = _userid
                });
                await _dbContext.SaveChangesAsync();
            }
            _channelHelper.WriteStatus(new StatusModel() { Action = 1, ModelType = 2, body = Newtonsoft.Json.JsonConvert.SerializeObject(backinfo) });
            return backinfo;
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> CreateRange(InputBody input)
        {
            var addnum = 0;
            var _userid = base.ReadCurrentAdminId();
            if (!string.IsNullOrEmpty(input.body))
            {
                var urls = input.body.Replace("；", ";").Replace(",", ";").Replace("，", ";");
                foreach (var url in urls.Split(';').Distinct())
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        if (url.StartsWith("http") && url.EndsWith("/"))
                        {
                            //排重
                            var find = _dbContext.NodeInfo.Where(x => x.Url == url).AsNoTracking().FirstOrDefault();
                            if (find == null || find == default)
                            {
                                var one = new NodeInfo()
                                {
                                    IsEnable = true,
                                    Url = url,
                                    Group = "slave",
                                    Status = NodeStatus.normal,
                                    JoinToken = Guid.NewGuid().ToString().Replace("-", "").ToLower(),
                                    Token = Guid.NewGuid().ToString().Replace("-", "").ToLower()
                                };
                                _dbContext.Add(one);
                                addnum++;
                            }
                            //写入
                        }
                    }
                }
            }
            if (addnum > 0)
            {
                await _dbContext.SaveChangesAsync();
                var find_group = _dbContext.NodeGroupInfo.Where(x => x.Name == "slave").Select(x => x.Id).FirstOrDefault();
                if (find_group == 0)
                {
                    _dbContext.Add(new NodeGroupInfo
                    {
                        Name = "slave",
                        Description = "",
                        Sort = 1,
                        UserId = _userid
                    });
                    await _dbContext.SaveChangesAsync();
                }
            }
            else
            {
                throw new Exception("输入数据不符合规则，没有新增节点信息！");
            }
            return "批量新增成功";
        }

        /// <summary>
        /// 更新一个节点信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<NodeInfoDto> UpdateItemAsync(NodeInfoUpdateDto input)
        {
            var _userid = base.ReadCurrentAdminId();
            var info = await _dbContext.NodeInfo.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new UserFriendlyException("需要查询的信息不存在", "404");
            }
            if (input.IsEnable)
            {
                input.Status = NodeStatus.running;
            }
            else
            {
                input.Status = NodeStatus.stop;
            }
            ObjectMapper.Map<NodeInfoUpdateDto, NodeInfo>(input, info);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<NodeInfo, NodeInfoDto>(info);
            var find_group = _dbContext.NodeGroupInfo.Where(x => x.Name == input.Group).Select(x => x.Id).FirstOrDefault();
            if (find_group == 0)
            {
                _dbContext.Add(new NodeGroupInfo
                {
                    Name = input.Group,
                    Description = "",
                    Sort = 1,
                    UserId = _userid
                });
                await _dbContext.SaveChangesAsync();
            }
            _channelHelper.WriteStatus(new StatusModel() { Action = 2, ModelType = 2, body = Newtonsoft.Json.JsonConvert.SerializeObject(backinfo) });
            return backinfo;
        }

        /// <summary>
        /// 删除节点信息软删除
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> DeleteItemById(int id)
        {
            var aione = await _dbContext.NodeInfo.Where(xy => xy.Id == id).FirstOrDefaultAsync();//.FirstOrDefault();
            if (aione != default)
            {
                //await _repository.DeleteAsync(aione);
                _dbContext.Remove(aione);
                await _dbContext.SaveChangesAsync();
                _channelHelper.WriteStatus(new StatusModel() { Action = 3, ModelType = 2, body = $"{id}" });
            }
            return 1;
        }

    }
}
